package com.kingtone.rongji.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.R;
import com.kingtone.rongji.adapter.CategoryLeftAdapter;
import com.kingtone.rongji.adapter.CategoryRightAdapter;
import com.kingtone.rongji.biz.ProductCategory;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class CategoryFragment extends Fragment implements OnItemClickListener {
	private String tag = "CategoryFragment";
	
	// 第二级分类目录
	private ListView mLeftListView;
	private CategoryLeftAdapter mLeftAdapter;
	private List<ProductCategory> rawData1 = new ArrayList<ProductCategory>();
	
	// 第三级分类目录
	private GridView mRightGridView;
	private CategoryRightAdapter mRightAdapter;
	private List<ProductCategory> rawData2 = new ArrayList<ProductCategory>();
	
	// 当前选中分类
	private TextView mCname;
	//private String mCurrentCategory = "-1";// Init all
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(tag, "onCreateView");
		View view = initView(inflater);
		initData();
		return view;
	}
	
	private View initView(LayoutInflater inflater) {
		View view = inflater.inflate(R.layout.fragment_category, null);
		
		view.findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MainActivity main = (MainActivity) getActivity();
				main.setCurrentTab("Dashboard", null);
			}
		});
		
		((TextView) view.findViewById(R.id.title)).setText("分类");
		
		PullToRefreshScrollView scrollview = (PullToRefreshScrollView) view.findViewById(R.id.all_layout);
		scrollview.setMode(PullToRefreshBase.Mode.DISABLED);
		
		mLeftListView = (ListView) view.findViewById(R.id.left_list);
		mLeftAdapter = new CategoryLeftAdapter(getActivity());
		mLeftListView.setAdapter(mLeftAdapter);
		mLeftListView.setOnItemClickListener(this);
		
		mRightGridView = (GridView) view.findViewById(R.id.right_list);
		mRightAdapter = new CategoryRightAdapter(getActivity());
		mRightGridView.setAdapter(mRightAdapter);
		mRightGridView.setOnItemClickListener(this);
		
		mCname = (TextView) view.findViewById(R.id.c_name);
		return view;
	}
	
	private void initData2() {
		RongJiRestClient.getCategory("3", new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				if(arg0==200) {
					try {
						String responseText = new String(arg2);
						Log.d(tag, "Result:" + responseText);
						
						Gson gson = new Gson();
						JsonParser parser = new JsonParser();
						JsonArray array = parser.parse(responseText).getAsJsonArray();
						List<ProductCategory> list = new ArrayList<ProductCategory>();
						for(JsonElement obj:array) {
							ProductCategory object = gson.fromJson(obj, ProductCategory.class);
							list.add(object);
						}
						
						rawData2.clear();
						rawData2.addAll(list);
						mRightAdapter.addAll(list);
						setGridViewHeightBasedOnChildren(mRightGridView);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					Log.e(tag, "Error:code=" + arg0);
				}
				
				RongJiUtils.dismissProgress();
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				RongJiUtils.dismissProgress();
				Log.e(tag, "Failed:code=" + arg0);
				if(null != arg3) {
					arg3.printStackTrace();
				}
			}
		});
	}
	
	private void initData() {
		RongJiUtils.showEmptyProgress(getActivity());
		RongJiRestClient.getCategory("2", new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				if(arg0==200) {
					try {
						String responseText = new String(arg2);
						Log.d(tag, "Result:" + responseText);
						
						Gson gson = new Gson();
						JsonParser parser = new JsonParser();
						JsonArray array = parser.parse(responseText).getAsJsonArray();
						List<ProductCategory> list = new ArrayList<ProductCategory>();
						for(JsonElement obj:array) {
							ProductCategory object = gson.fromJson(obj, ProductCategory.class);
							list.add(object);
						}
						
						rawData1.clear();
						rawData1.addAll(list);
						mLeftAdapter.addAll(list);
						setListViewHeightBasedOnChildren(mLeftListView);
						
						initData2();
					} catch(Exception e) {
						RongJiUtils.dismissProgress();
						e.printStackTrace();
					}
				} else {
					RongJiUtils.dismissProgress();
					Log.e(tag, "Error:code=" + arg0);
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				RongJiUtils.dismissProgress();
				Log.e(tag, "Failed:code=" + arg0);
				if(null != arg3) {
					arg3.printStackTrace();
				}
			}
		});
	}
	
	private String getLeftCategoryIdByIndex(int index) {
		if(index>=0 && index<rawData1.size()) {
			return rawData1.get(index).getCategoryId();
		}
		return "-1";
	}
	
	private List<ProductCategory> getCategoryByParent(String pid) {
		List<ProductCategory> result = new ArrayList<ProductCategory>();
		if(pid.equals("-1")) {// All
			result.addAll(rawData2);
		} else {
			for(ProductCategory item : rawData2) {
				if(item.getParentCategoryId().equals(pid)) {
					result.add(item);
				}
			}
		}
		return result;
	}
	
	private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter adapter = listView.getAdapter();
        if(adapter != null) {
            int totalHeight = 0;
            for(int i=0; i<adapter.getCount(); i++) {
                View listItem = adapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
            ((ViewGroup.MarginLayoutParams) params).setMargins(0, 0, 0, 0);
            listView.setLayoutParams(params);
        }
    }
	
	@SuppressLint("NewApi")
	private void setGridViewHeightBasedOnChildren(GridView listView) {
        ListAdapter adapter = listView.getAdapter();
        if(adapter != null) {
            int totalHeight = 0;
            for(int i=0; i<adapter.getCount(); ) {
                View listItem = adapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += (listItem.getMeasuredHeight() + listView.getVerticalSpacing());
                i+=3;
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            
            int selfHeight = totalHeight + (adapter.getCount() - 1) + 50;
            int leftHeight = mLeftListView.getLayoutParams().height;
            
            params.height = Math.max(selfHeight, leftHeight);
            ((ViewGroup.MarginLayoutParams) params).setMargins(0, 0, 0, 0);
            listView.setLayoutParams(params);
        }
    }

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if(arg0.getId()==R.id.right_list) {
			ProductCategory pc = (ProductCategory) mRightAdapter.getItem(arg2);
			if(null!=pc) {
				MainActivity activity = (MainActivity) this.getActivity();
				activity.onQueryChanged(Integer.valueOf(pc.getCategoryId()), "", false);
			}
		} else {
			List<ProductCategory> list = getCategoryByParent(getLeftCategoryIdByIndex(arg2));
			mRightAdapter.addAll(list);
			
			setGridViewHeightBasedOnChildren(mRightGridView);
			
			ProductCategory item = list.get(0);
			if(null!=item) {
				mCname.setText(item.getParentCategoryName());
			}
		}
	}
		
}
